/**
 * Created by xiaoz on 16/8/13.
 */
define(["utils", "base"], function (utils, baseClass) {
    function Component(config) {
        var _this = this;
        this.refs = {};
        this.componentsInitActions = {};
        this.componentsInitActionsArray = {};
        Component.baseConstructor.call(this, config);
        config.root = config.root || [];
        this.params = config.$$params;
        this.pagecontainer = config.pagecontainer;
        this.showPageDict = {};
        this.showPageParams = config.showPageParams || {};
        this.innerPageViewContainer = null;
        this.pageManager = config.$$pageManager;
        this.global = this.pageManager.global;
        this.registerHashChangeComponent = {};
        this.config = config;
        this.components = {};

        this.$el.addClass("yy-pageview");

        //初始化控制器
        var controller = config.pluginClass || config.controller;


        if(typeof controller == "function"){
            _this._preparePlugin(controller);
            this.pageResumeMethod = this.plugin.onPageResume;
            this.pageBeforeClose = this.plugin.onPageBeforeClose;
            this.initLayout();
            this.dialogs={};
            this.dialogsBks={};
        }else if(typeof controller == "string"){
            var path = "./controllers/"+controller;
            require([path],function(Control){
                //var Control = require(path);
                _this._preparePlugin(Control);
                _this.pageResumeMethod = _this.plugin.onPageResume;
                _this.pageBeforeClose = _this.plugin.onPageBeforeClose;
                _this.initLayout();
                _this.dialogs={};
                _this.dialogsBks={};
            });
        }else {
            console.error("controller is dismiss");
            return;
        }



    }

    utils.extendClass(Component, baseClass);

    Component.prototype._preparePlugin = function(controllerClass){
        this.plugin = new controllerClass({"pageview":this});
        var children = this.config.children;
        if(children && children instanceof Array && children.length>0){
            for(var i=0,j=children.length;i<j;i++){
                var pluginClass = children[i].pluginClass;
                if(pluginClass){
                    var pluginPart = new pluginClass();
                    this.plugin  = $.extend(true,this.plugin,pluginPart);
                }
            }
        }
    };

    Component.prototype.destory = function () {
        this.$el.remove();
    };

    /*
     {
     pageKey:"",
     mode:"fullscreen", or dialog
     style:{},// dialog有效
     params:{}
     }
     */

    Component.prototype.showTip = function (config) {
        var tipWrapper = $("<div class='yy-tip-wrapper'><div class='yy-tip'>" + (config.text || "") + "</div></div>");
        var isShowInCurrentPage = config.isShowInCurrentPage;
        if(isShowInCurrentPage){
            tipWrapper.css({"position":"absolute"});
            tipWrapper.appendTo(this.$el);
        }else{
            tipWrapper.appendTo(document.body);
        }
        tipWrapper.on("click",function(e){
            tipWrapper.remove();
        });
        window.setTimeout(function () {
            tipWrapper.remove();
        }, config.duration || 1500);
    };


    Component.prototype.showBackLayer=function(cb){
      var _this= this;
      if(!this.bkLayer ){
        this.bkLayer = $("<div class='yy-bk-layer'></div>");
        this.bkLayer.appendTo(document.body);
        this.bkLayer.bind("click",function(e){
            _this.hideCurShowPage();
        });

      }
      this.bkLayer.removeClass("displaynone");
      // this.bkLayer.fadeIn("fast");
    };
    Component.prototype.hideBackLayer = function(){
      if(this.bkLayer ){
        this.bkLayer.addClass("displaynone");

      }
    };
    //pageview里添加页面，添加的页面可以是dialog，滑出页，不计入路由
    Component.prototype.showPage = function (config) {
        var _this = this;
        var mode = config.mode || "dialog";
        config.mode = config.mode||"";
        this.showPageConfig = config;
        var showPageInfo = _this.showPageDict[config.pageKey];
        if(mode.toUpperCase() !== "OUTFULLSCREEN"){
          this.pageview.showBackLayer();
        }
        if (showPageInfo) {
            // this.curshowPage = showPageInfo;
            // showPageInfo.pageInstance.showPageParams = config.params || {};
            //
            // var onPageResumeMethod = showPageInfo.pageInstance.plugin.onPageResume;
            // onPageResumeMethod && onPageResumeMethod.call(showPageInfo.pageInstance.plugin);
            // showPageInfo.pageWrapper.removeClass("visibilityhidden");
            // return;
            showPageInfo.pageWrapper.remove();
        }



        this.pageview.pageManager.getPageConfigByPageKey(config.pageKey, function (pageConfig) {
            pageConfig.showPageParams = config.params || {};
            var slideKey = _this.pageview.config.pageKey+"_"+config.pageKey+"_sildepage";
            pageConfig.$$sildeKey = slideKey;
            pageConfig.ownerPage = _this;
            var page_instance = _this.pageview.pageManager.createPageView(pageConfig);
            page_instance.ownerPage = _this;
            var pageWrapper = $("<div></div>");
            if (mode.toUpperCase() === "FULLSCREEN") {
                _this.pageview.hideBackLayer();
                pageWrapper.addClass("yy-showpage-fullscreen");
                pageWrapper.appendTo(_this.pageview.$el);
                pageWrapper.append(page_instance.$el);
            } else if(mode.toUpperCase() === "SLIDE"){
                // _this.pageview.pageManager.regeistBodyClick(pageConfig.$$sildeKey,function(){
                //     page_instance.close();
                // });


                //清楚原来dom
                _this.pageview.$el.find('.yy-showpage-silde').remove();

                pageWrapper.addClass("yy-showpage-silde");


                pageWrapper.appendTo(_this.pageview.$el);

                pageWrapper.append(page_instance.$el);
                setTimeout(function () {

                    _this.pageview.$el.find('.yy-showpage-silde').removeClass("yy-showpage-silde-hide").addClass('yy-showpage-silde-show');
                }, 100);

                pageWrapper.append(page_instance.$el);
            }else if(mode.toUpperCase() === "OUTFULLSCREEN"){
              pageWrapper.addClass("yy-showpage-outfullscreen");
              pageWrapper.append(page_instance.$el);
              pageWrapper.append(pageDialogInnerWrap);
              pageWrapper.appendTo(document.body);
            }else{
                pageWrapper.addClass("yy-showpage-dialog");
                var span = $("<span class='yy-showpage-dialog-mid'></span>");
                var pageDialogInnerWrap = $("<div class='yy-showpage-dialog-inner'></div>");
                pageDialogInnerWrap.append(page_instance.$el);
                //.append(span)
                pageWrapper.append(pageDialogInnerWrap);
                pageWrapper.appendTo(document.body);
            }
            if(config.className){
              pageWrapper.addClass(config.className);
            }
            _this.curshowPage = {pageInstance: page_instance, pageWrapper: pageWrapper};
            if (pageConfig.nocache !== true) {
                _this.showPageDict[config.pageKey] = {pageInstance: page_instance, pageWrapper: pageWrapper};
            }

        });

    };

    // 关闭页面
    Component.prototype.close = function () {
        this.pageview.hideBackLayer();
        if (this.ownerPage) {
            this.ownerPage.hideCurShowPage();
        }
    };

    Component.prototype.beforeClose = function () {

      if(this.pageBeforeClose){
        var Re = this.pageBeforeClose.call(this.plugin);
        return Re;
      }else{
        return true;
      }
    };



    //隐藏当前页面
    Component.prototype.hideCurShowPage = function () {
        if (this.curshowPage) {
            var Re = this.curshowPage.pageInstance.beforeClose();
            if(Re === false){
              return;
            }
            this.pageview.hideBackLayer();
            this.pageResumeMethod && this.pageResumeMethod.call(this.plugin);
            if (this.showPageConfig.mode && this.showPageConfig.mode.toUpperCase() === "SLIDE") {
                this.curshowPage.pageWrapper.removeClass("yy-showpage-silde-show").addClass('yy-showpage-silde-hide');

            } else {
                this.curshowPage.pageWrapper.addClass("displaynone");
            }
            this.curshowPage = null;
        }
    };

    Component.prototype.ajax = function (config) {
        config.pageviewInstance = this;
        utils.ajax(config);
    };
    //.removeClass("yy-dialog-hide").addClass("yy-dialog-show");
    //直接showdialog
    Component.prototype.showDialog = function (key,config) {
        var _this = this;
        config =config||{};
        var dialog = this.dialogs[key];
        if(dialog){
        this.dialogs[key].removeClass("yy-dialog-hide").addClass("yy-dialog-show");
         this.dialogsBks[key].removeClass("displaynone");
          return;
        }
        var datasource = config.datasource;
        this.getComponentInstanceByComKey(key, datasource, null, function (com_instance) {
            var dialogWrapper = $("<div class='yy-dialog-out-wrap'></div>");
            if(config.zIndex){
              dialogWrapper.css({zIndex:config.zIndex+1});
            }
            var dialogInnerWrap = $("<div class='yy-dialog-inner-wrap'></div>");
            _this.dialogs[key] = dialogWrapper;
            dialogInnerWrap.append(com_instance.$el);
            dialogWrapper.append(dialogInnerWrap);
            dialogWrapper.appendTo(document.body);

            var dialogBK = $("<div class='yy-dialog-bk'></div>");
            if(config.zIndex){
              dialogBK.css({zIndex:config.zIndex});
            }
            _this.dialogsBks[key]  = dialogBK;
            dialogBK.appendTo(document.body);
            dialogWrapper.removeClass("yy-dialog-hide").addClass("yy-dialog-show");
        }, function (e) {
        })
    };

    Component.prototype.hideDialog = function (key) {
        // this.dialogs[key].remove();
        this.dialogsBks[key].addClass("displaynone");
        this.dialogs[key].addClass("yy-dialog-hide").removeClass("yy-dialog-show");

        // this.dialogsBks[key].remove();
    };

    Component.prototype.triggerPageContainerHashChange = function (routes) {
        this.routes = routes;
        if (this.innerPageViewContainer) {

            this.innerPageViewContainer.hashChange(routes);
        } else {
            this.innerPageViewContainerNeedTriggerHashChange = true;
        }
    };
    Component.prototype.hashChange = function (routes) {
        this.curRoutes = utils.copy(routes);
        this.triggerPageContainerHashChange(routes);
        for (var key in this.registerHashChangeComponent) {
            var com = this.registerHashChangeComponent[key];
            com && com.hashChange && com.hashChange();
        }
    };


    Component.prototype.delegate = function (com_key, action) {
        var com_instance = this.refs[com_key];

        if (com_instance) {
            action(com_instance);
        } else {
            if (!this.config.components[com_key].ref) {
                console.log("请务必在" + com_key + "控件上设置ref:true");
            }
            this.componentsInitActions[com_key] = action;
        }
    };

    Component.prototype.delegates = function (com_key, action) {
        var com_instance = this.refs[com_key];

        if (com_instance) {
            action(com_instance);
        } else {
            if (!this.config.components[com_key].ref) {
                console.log("请务必在" + com_key + "控件上设置ref:true");
            }
            if(!this.componentsInitActionsArray[com_key]){
                this.componentsInitActionsArray[com_key] = [];
            }
            this.componentsInitActionsArray[com_key].push(action);
        }
    };


    Component.prototype.goBack = function () {
        this.pageManager.goBack();
    };

    Component.prototype.go = function (pageKey, params) {
        params = params || {};
        var beforeGoMethod = this.pageManager.appConfig.beforeGo;
        if (beforeGoMethod) {
            beforeGoMethod({params: params, pageviewInstance: this});
        }
        this.pageManager.go(pageKey, params);
    };

    Component.prototype.replaceGo = function(pageKey,params){
       params = params||{};
      var beforeGoMethod  =this.pageManager.appConfig.beforeGo;
      if(beforeGoMethod){
        beforeGoMethod({params:params,pageviewInstance:this});
      }
        this.pageManager.replaceGo(pageKey,params);
    };


    return Component;

});
